<template>
    <div class="config-wrapper">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="180px" @submit.native.prevent>
            <el-row :gutter="30">
                <el-col :span="12">
                    <h2 style="margin-bottom:16px;">积分配置</h2>
                    <el-form-item label="用户初始积分" prop="initial_points">
                        <el-input v-model.number="form.initial_points" type="number" min="0"
                            @input="intInput('initial_points')" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="生成一次消耗积分" prop="compose_song_cost">
                        <el-input v-model.number="form.compose_song_cost" type="number" min="0"
                            @input="intInput('compose_song_cost')" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>


            <el-form-item>
                <el-button type="primary" :loading='load' @click="onSubmit">保存配置</el-button>
            </el-form-item>
        </el-form>
        <div style="margin: 0;">
            <el-form :model="form1" :rules="rules" ref="formRef1" @submit.native.prevent>
                <el-row>
                    <el-col :span="24">
                        <h2 style="margin-bottom:16px;">内购积分配置</h2>
                        <el-form-item label="">
                            <div v-for="(item, i) in list" :key="item.id"
                                style="margin-bottom:12px;display:flex;align-items:center;">
                                <span style="width:120px;display:inline-block;">{{ item.product_id }}</span>

                                <span style="margin:0 8px;">原价</span>
                                <el-input v-model.number="item.original_price" type="number" min="0"
                                    style="width:100px;" size="small" clearable :step="0.01"
                                    placeholder="原价"></el-input>

                                <span style="margin:0 8px;">现价</span>
                                <el-input v-model.number="item.current_price" type="number" min="0" style="width:100px;"
                                    size="small" clearable :step="0.01" placeholder="现价"></el-input>

                                <span style="margin:0 8px;">折扣率</span>
                                <el-input v-model.number="item.discount_rate" type="number" min="0" max="1"
                                    style="width:100px;" size="small" clearable :step="0.01"
                                    placeholder="1.00" ></el-input>

                                <span style="margin:0 8px;">积分数量</span>
                                <el-input v-model.number="item.points" type="number" min="0" style="width:100px;"
                                    size="small" clearable placeholder="积分数量"></el-input>

                                <el-button style="margin-left:20px;" type="primary" size="small"
                                    @click="submitEditProduct(item)">
                                    保存
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>


        </div>
    </div>
</template>

<script>
import { pointsProducts, pointsConfig, pointsProductUpdate, pointsConfigUpdate } from "@/api/museo";

import axios from "axios";
export default {
    name: "ConfigForm",
    data() {
        const checkInt = (rule, value, callback) => {
            if (value === undefined || value === null || value === "") {
                callback(new Error("必填项"));
            } else if (!/^\d+$/.test(String(value))) {
                callback(new Error("请输入非负整数"));
            } else {
                callback();
            }
        };
        const checkDecimal1 = (rule, value, callback) => {
            if (value === undefined || value === null || value === "") {
                callback(new Error("必填项"));
            } else if (!/^\d+(\.\d)?$/.test(String(value))) {
                callback(new Error("最多1位小数"));
            } else {
                callback();
            }
        };
        return {
            list: [],
            form: {
                compose_song_cost: 0,
                initial_points: 0
            },
            rules: {
                regular_feature_minutes: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_photos_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_feature_minutes: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_photos_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_tokens_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_tokens_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_float_copy_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_float_copy_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                regular_quick_text_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                member_quick_text_limit: [{ required: true, validator: checkInt, trigger: "blur" }],
                redeem_tokens_per_10_momo: [{ required: true, validator: checkInt, trigger: "blur" }],

                web_capture_per_piece: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                float_copy_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                quick_capture_per_piece: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                quick_text_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                accurate_minute_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                quick_translate_minute_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
                comic_realtime_minute_per_time: [{ required: true, validator: checkDecimal1, trigger: "blur" }],
            },
            msg: '',
            msgType: 'success',
            load: false
        };
    },
    created() {
        this.getConfig();
        this.getConfig1();
    },
    methods: {
        decimal1Input(field) {
            let val = this.form[field];
            // 只允许正数和一位小数
            if (val === "" || val == null) return;
            val = String(val)
                .replace(/[^\d.]/g, "")           // 只保留数字和点
                .replace(/^\./g, "")              // 小数点不能开头
                .replace(/\.{2,}/g, ".")          // 不能有连续点
                .replace(".", "#").replace(/\./g, "").replace("#", ".") // 只第一个点
                .replace(/^(\d+)\.(\d).*$/, "$1.$2"); // 最多保留一位小数
            if (val !== "" && !isNaN(val)) {
                this.form[field] = parseFloat(val);
            }
        },
        onCoinInput(type, idx, val) {
            val = Number(val)
            if (val < 0 || isNaN(val)) val = 0; // 保证非负整数
            if (type === 'base') this.list[idx].base_coins = val
            if (type === 'bonus') this.list[idx].bonus_coins = val
        },
        async submitEditCoinRule(row) {
            if (!row.product_id) {
                this.$message.error('商品ID不能为空');
                return;
            }
            if (row.base_coins == null || isNaN(row.base_coins)) {
                this.$message.error('基础币数不能为空');
                return;
            }
            if (row.bonus_coins == null || isNaN(row.bonus_coins)) {
                this.$message.error('赠送币数不能为空');
                return;
            }
            try {
                let res = await axios.post('https://xiaoshuchengzhang.com/node/Transir/product-coin-rules/edit', {
                    product_id: row.product_id,
                    base_coins: row.base_coins,
                    bonus_coins: row.bonus_coins
                });
                if (res.data.code === 0) {
                    this.$message.success('修改成功');
                    // 可选：刷新list
                    this.getConfig1();
                } else {
                    this.$message.error(res.data.msg || '保存失败');
                }
            } catch (e) {
                this.$message.error('接口请求失败');
            }
        },
        intInput(field) {
            this.form[field] = String(this.form[field]).replace(/[^\d]/g, "");
            if (this.form[field] !== "") {
                this.form[field] = parseInt(this.form[field], 10);
            }
        },
        async getConfig() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            try {
                const { data } = await pointsConfig();
                loading.close();
                // 把后端的秒数转为分钟（向下取整，或四舍五入都行）
                this.form.initial_points = data.initial_points;
                this.form.compose_song_cost = data.compose_song_cost;
            } catch (e) {
                this.msg = "获取配置失败";
                this.msgType = "error";
            }
        },
        async getConfig1() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            let res = await pointsProducts();
            console.log(res)
            loading.close();
            this.list = res.list
        },
        async submitEditProduct(item) {
            // 校验字段
            if (!item.product_id || item.original_price < 0 || item.current_price < 0 || item.points < 0) {
                this.$message.error('请完善商品ID、价格和积分数量');
                return;
            }
            await pointsProductUpdate({
                id: item.id,
                product_id: item.product_id,
                original_price: item.original_price,
                current_price: item.current_price,
                discount_rate: item.discount_rate,
                points: item.points
            })
            await this.getConfig1()
        },

        onSubmit() {
            this.$refs.formRef.validate(async (valid) => {
                if (valid) {
                    this.$confirm(
                        '确定要保存该配置吗？',
                        '二次确认',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(async () => {
                        this.load = true;

                        // 可根据你的业务做字段调整：
                        const payload = {
                            ...this.form,
                            // 如有需要换算的字段可以这里处理
                            // regular_feature_minutes: this.form.regular_feature_minutes * 60,
                            // member_feature_minutes: this.form.member_feature_minutes * 60
                        };

                        try {
                            let res = await pointsConfigUpdate(payload);
                            let data = res;
                            if (data.success) {
                                this.$message({
                                    message: data.msg || '保存成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: data.msg || '保存失败',
                                    type: 'error'
                                });
                            }
                        } catch (e) {
                            this.$message({
                                message: '保存失败，网络异常',
                                type: 'error'
                            });
                        }
                        this.load = false;

                    }).catch(() => {
                        this.load = false;
                        this.$message({
                            message: "已取消操作",
                            type: "info"
                        });
                    });
                }
            });
        }


    }

};
</script>

<style scoped>
.config-wrapper {
    background: #fff;
    border-radius: 8px;
    padding: 28px 18px 38px 18px;
    margin: 0 auto;
    max-width: 1000px;
}

.notice {
    margin-top: 20px;
    font-size: 15px;
    padding: 10px 14px;
    border-radius: 8px;
}

.success {
    background: #e5f6ec;
    color: #15a167;
}

.error {
    background: #ffdbe9;
    color: #cd2323;
}
</style>
